package com.qf.myshop.shop_zuul.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.myshop.shop_entity.ResultData;
import com.qf.myshop.shop_zuul.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthFilter extends ZuulFilter {
    @Value("${white.path}")
    private String whitePath;
    @Resource
    private UserService userService;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("过滤器正在执行...");
        // 处理白名单
        // 不过滤的路径处理
        // 得到请求对象
        final RequestContext context = RequestContext.getCurrentContext();
        final HttpServletRequest request = context.getRequest();
        final HttpServletResponse response = context.getResponse();
        // 如果不是白名单范畴，需要验证身份
        if (!isWhitePath(request.getRequestURI())){
            // 验证身份
            final String token = request.getHeader("token");
            final ResultData data = userService.check(token);
            // 如果验证不成功
            if (!data.getCode().equals("10000")){
//                context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
                context.setSendZuulResponse(false);
                response.setContentType("application/json;charset=utf-8");
                ObjectMapper mapper = new ObjectMapper();
                final String s;
                try {
                    s = mapper.writeValueAsString(data);
                    System.out.println(s);
                    response.getWriter().write(s);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    private boolean isWhitePath(String uri){
        if (whitePath != null){
            final String[] strings = whitePath.split(",");
            if (strings != null){
                for (String string : strings) {
                    if (uri.endsWith(string)){
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
